package org.zqh.ncc.thread;

import com.alibaba.fastjson.JSON;
import nccloud.open.api.auto.token.cur.utils.APICurUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Component;
import org.zqh.ncc.config.YfymToErp;
import org.zqh.ncc.config.SysConfig;
import org.zqh.ncc.ncmodel.*;
import org.zqh.ncc.ncmodel.DH.BillInfo;
import org.zqh.ncc.ncmodel.DH.JsonRootBean;
import org.zqh.ncc.ncmodel.DH.Po_order;
import org.zqh.ncc.ncmodel.DH.Po_order_b;
import org.zqh.ncc.utils.TimeUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 定时扫描t_bangdan表，发现有需要推NC单据的记录，就进行处理,该线程只处理源发玉米
 */
@Component("yfymToErpThread")
public class YfymToErpThread extends CommonThread<YfymToErp> {
    volatile long beginTime = 0;
    SysConfig sysConfig;
    APICurUtils apiCurUtils;
    String token;

    /**
     *
     */
    @Autowired
    public YfymToErpThread(@Qualifier("yfymToErpQueue") PriorityBlockingQueue<YfymToErp> yfymToErpQueue, APICurUtils apiCurUtils, SysConfig sysConfig) {
        super(yfymToErpQueue);
        this.apiCurUtils = apiCurUtils;
        this.sysConfig = sysConfig;
        apiCurUtils.init(sysConfig.getIp(), sysConfig.getPort(), sysConfig.getBiz_center(), sysConfig.getClient_id(), sysConfig.getClient_secret(), sysConfig.getPubKey(), sysConfig.getUser_name(), sysConfig.getPwd());
//        try {
//            token = apiCurUtils.getToken();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        this.setName("bdToErpThread");


    }

    /**
     * 线程启动运行，推送状态报告
     */
    public void run() {
        while (!isStopping) {
            try {
                List<YfymToErp> bdList = getYfymToErpList(10);
                if (bdList.size() > 0) {
                    processList(bdList);
                    beginSleep(100);
                } else {
                    beginSleep(3000);
                }
            } catch (Exception e) {
                log.error("", e);
                beginSleep(10000);
            }
        }
        isStopped = true;
    }

    /**
     * @param bdList
     */
    private void processList(List<YfymToErp> bdList) {
        beginTime = System.currentTimeMillis();
        for (YfymToErp yfymToErp : bdList) {
            log.debug("before yfymToErp post :" + yfymToErp);
            try {
                token = apiCurUtils.getToken();
                apiCurUtils.setApiUrl(sysConfig.getUrl());
                String sendJson = toErpPoOrder(yfymToErp);
                log.info("send: " + sendJson);
                String apiRetrun = apiCurUtils.getAPIRetrun(token, sendJson);
                log.info((System.currentTimeMillis() - beginTime) + " ms return: " + apiRetrun);
                NcBillReturn ncBillReturn = JSON.parseObject(apiRetrun, NcBillReturn.class);
                if (null != ncBillReturn) {
                    if (null == ncBillReturn.getMessage())
                        ncBillReturn.setMessage("null");
                    else if (ncBillReturn.getMessage().length() > 300) {
                        ncBillReturn.setMessage(ncBillReturn.getMessage().replaceAll("'", "#"));
                        ncBillReturn.setMessage(ncBillReturn.getMessage().substring(ncBillReturn.getMessage().length() - 298));
                    }
                    String sql = "update t_bangdan set resulttime=sysdate,resultmemo='" + ncBillReturn.getMessage() + "',resulttoerp='" + (ncBillReturn.isSuccess() ? "1" : "-1") +
                            "' where vbdcode='" + yfymToErp.getVbdcode() + "'";
                    try {
                        jdbcTemplate.update(sql);
                    } catch (Exception sqlError) {
                        log.error("sql=" + sql, sqlError);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("调用接口错误：", e);
            }
        }
    }

    /**
     * 先更新t_bangdan表，加上一个uuid,后面根据这个uuid进行select，更新那些需要同步推送到NC的过磅单，根据resulttoerp字段的值
     *
     * @param count 每次处理的数量
     * @return
     */
    private List<YfymToErp> getYfymToErpList(int count) {
        List<YfymToErp> bdList = new ArrayList<>();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        int rowCount = 0;
        String sql = "update t_bangdan set resulttoerp='2',updateuuid='" + uuid + "' where vbdtype='DH' and resulttoerp='0' and rownum <= " + count;
        try {
            rowCount = jdbcTemplate.update(sql);
        } catch (Exception sqlError) {
            log.error("sql=" + sql, sqlError);
        }
        if (rowCount > 0) {
            bdList = jdbcTemplate.query("select * from v_bangdan where updateuuid='" + uuid + "'", new BeanPropertyRowMapper(YfymToErp.class));
            if (bdList.size() != rowCount) {
                log.warn("uuid=" + uuid + " updateCount=" + rowCount + " getCount=" + bdList.size() + ", 注意检查");
            }
        }
        return bdList;
    }

    /**
     * 从视图返回的对象，转换为json，传递给NC接口，推式生成采购订单
     *
     * @param yfymToErp
     * @return
     */
    private String toErpPoOrder(YfymToErp yfymToErp) {
        JsonRootBean jb = new JsonRootBean();
        BillInfo billInfo = new BillInfo();
        Po_order po_order = new Po_order();
        Po_order_b po_order_b = new Po_order_b();
        po_order.setBillmaker(yfymToErp.getBillmaker());
        po_order.setPk_dept(yfymToErp.getPkdept());
        po_order.setPk_org(yfymToErp.getPkorg());
        po_order.setPk_org_v(yfymToErp.getPkorg());
        po_order.setVtrantypecode(yfymToErp.getVtrantypecode());
        po_order.setDbilldate(TimeUtil.getStrDateFormat(new Date()));
        po_order.setPk_supplier(yfymToErp.getVfromcode());
        po_order.setPk_invcsupllier(yfymToErp.getVfromcode());
        po_order.setVdef21(yfymToErp.getInspector());
        po_order.setVdef22(yfymToErp.getVuncart());
        //冲销的单据，算作退货，需要设置breturn=Y
        if (yfymToErp.getVbdcode().indexOf("-") > 0)
            po_order.setBreturn("Y");
        else
            po_order.setBreturn("N");

        po_order_b.setCorigcurrencyid(yfymToErp.getOrigcurrencyid());
        po_order_b.setCtaxcodeid(yfymToErp.getTaxcodeid());
        po_order_b.setPk_material(yfymToErp.getVmatcode());
        po_order_b.setNqtorigtaxprice(yfymToErp.getNprice());
        po_order_b.setVbdef14("" + yfymToErp.getNpizhong());
        po_order_b.setVbdef15(TimeUtil.getStrDateFormat(yfymToErp.getDouttime()));
        po_order_b.setVbdef16("" + yfymToErp.getNmaozhong());
        po_order_b.setVbdef17(TimeUtil.getStrDateFormat(yfymToErp.getDintime()));
        po_order_b.setVbdef18("" + yfymToErp.getNjingzhong());
        po_order_b.setVbdef19(yfymToErp.getVcarno());
        po_order_b.setVbdef20(yfymToErp.getVbdcode());

        po_order_b.setPk_recvstordoc(yfymToErp.getVstorname());

        int ibwc = Math.round(yfymToErp.getNjingzhong() * yfymToErp.getPkouwater() / 100);
        po_order_b.setVbdef29("" + ibwc);//扣水重

        int ibmz = Math.round(yfymToErp.getNjingzhong() * yfymToErp.getPkouza() / 100);
        po_order_b.setVbdef30("" + ibmz);//扣杂重
        //po_order_b.setVbdef30("" + yfymToErp.getNzazhong());//扣杂重

        int ibm = Math.round(yfymToErp.getNjingzhong() * yfymToErp.getPkoumb() / 100);
        po_order_b.setVbdef31("" + ibm);//扣霉变

        int ibi = Math.round(yfymToErp.getNjingzhong() * yfymToErp.getPkoubjz() / 100);
        po_order_b.setVbdef32("" + ibi);//扣并肩杂

        int ibbd = Math.round(yfymToErp.getNjingzhong() * yfymToErp.getPkourz() / 100);
        po_order_b.setVbdef44("" + ibbd);//扣容重
        //主数量是结算净重，=过磅净重-扣水杂后的重量
        po_order_b.setNnum(yfymToErp.getNjszhong());

        po_order_b.setVbdef33("" + yfymToErp.getNkouzhong());//皮重附加,一般用于微调净重，正数为加，负数为减
        po_order_b.setVbdef34("" + yfymToErp.getNsxwzhong());//筛下物
        po_order_b.setVbdef35("" + yfymToErp.getPwater());//水份%
        po_order_b.setVbdef36("" + yfymToErp.getPza());//杂质%
        po_order_b.setVbdef37("" + yfymToErp.getPmb());//霉变%
        po_order_b.setVbdef38("" + yfymToErp.getPbjz());//并肩杂%
        po_order_b.setVbdef39("" + yfymToErp.getPkouwater());//扣水份%
        po_order_b.setVbdef40("" + yfymToErp.getPkouza());//扣杂质%
        po_order_b.setVbdef41("" + yfymToErp.getPkourz());//扣容重%
        po_order_b.setVbdef42("" + yfymToErp.getPkoumb());//扣霉变%
        po_order_b.setVbdef43("" + yfymToErp.getPkoubjz());//扣并肩杂%
        po_order_b.setVbdef45(yfymToErp.getVqccode());//质验单编号
        po_order_b.setVbdef47(yfymToErp.getVinjby());//监磅员
        po_order_b.setVbdef48(yfymToErp.getVingby());//过磅员
        po_order_b.setVbdef49("" + yfymToErp.getPrz());//容重
        billInfo.setPo_order(po_order);
        List<Po_order_b> blist = new ArrayList<>();
        blist.add(po_order_b);
        billInfo.setPo_order_b(blist);
        List<BillInfo> billInfoList = new ArrayList<>();
        billInfoList.add(billInfo);
        jb.setBillInfo(billInfoList);
        jb.setFuncType("CREATE_PU_ORDER");

        return JSON.toJSONString(jb);
    }

}
